import md5 from "../js_sdk/md5/md5";
export function editSign(obj) {
  const timp = new Date().getTime();
  const nonce = generateRandomString(32);
  //    const nonce = generateRandomString(32);
  let sign = "";
  sign = genSignParams(obj, timp, nonce);
  return {
    "X-Nonce": nonce,
    "X-Timestamp": timp,
    "X-Sign": sign,
  };
}
function genSignParams(obj, timp, nonce) {
  const inObject = Object.assign({}, obj);
  var sorter = function (inObject) {
    var sortedJson = {};
    var sortedKeys = Object.keys(inObject).sort();
    for (var i = 0; i < sortedKeys.length; i++) {
      sortedJson[sortedKeys[i]] = inObject[sortedKeys[i]];
    }
    return sortedJson;
  };
  var sortedParam = sorter(inObject);

  var needSignatureStr = "";

  needSignatureStr = convertObjectToQueryString(sortedParam);
  const secretKey = "WQBymFuoi5okgiODmLSCbSIvT2PQla8ctWJxkDH7PEqBmfZmnTu8zeFRS4jAo7";
  if (needSignatureStr) {
    needSignatureStr += `&timestamp=${timp}&nonce=${nonce}&secret=${secretKey}`;
    return md5(needSignatureStr).toString().toUpperCase();
  } else {
    needSignatureStr = `timestamp=${timp}&nonce=${nonce}&secret=${secretKey}`
    return md5(needSignatureStr).toString().toUpperCase();
  }
}

function convertObjectToQueryString(obj) {
  const queryStringParts = [];

  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      let value = obj[key];

      // 只处理非空字符串、非空数组、非以 'https://' 开头的字符串
      if (typeof value === "string") {
        if (value.length > 0 && !value.startsWith("https://")) {
          queryStringParts.push(
            `${(key)}=${(value)}`
          );
        }
      } else if (Array.isArray(value) && value.length > 0) {
        value.forEach((val) => {
          if (typeof val === "string" && !val.startsWith("https://")) {
            queryStringParts.push(
              `${(key)}=${(val)}`
            );
          }
        });
      } else if (typeof value === "number") {
        // 对于数字字段，直接添加
        queryStringParts.push(
          `${(key)}=${(value)}`
        );
      }
    }
  }

  return queryStringParts.join("&");
}

function generateRandomString(length) {
  const charset =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  let result = "";
  for (let i = 0; i < length; i++) {
    const randomChar = charset[Math.floor(Math.random() * charset.length)];
    result += randomChar;
  }
  return result;
}
